<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useCustomerServiceStore } from "@/store/modules/customerService";
import { type ChatRoom, getAllChatRooms, deleteChatRoom } from "@/api/customer-service";
import { Refresh } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

defineOptions({
  name: "ChatRoomManagement"
});

const router = useRouter();
const store = useCustomerServiceStore();

// 查询与筛选
const searchForm = ref({
  room_id: "",
  nickname: ""
});

// 分页
const pagination = ref({ page: 1, pageSize: 10, total: 0 });
const loading = ref(false);
const rooms = ref<ChatRoom[]>([]);

/**
 * 加载聊天室列表（服务端分页）
 */
async function loadRoomsList() {
  try {
    loading.value = true;
    const { data }: any = await getAllChatRooms({
      page: pagination.value.page,
      per_page: pagination.value.pageSize,
      room_id: searchForm.value.room_id,
      nickname: searchForm.value.nickname
    });
    rooms.value = data?.rooms ?? [];

    const total = data?.pagination?.total ?? rooms.value.length;
    const page = data?.pagination?.page ?? pagination.value.page;
    const per = data?.pagination?.per_page ?? pagination.value.pageSize;
    pagination.value = { page, pageSize: per, total };
  } catch (error) {
    console.error("加载聊天室列表失败:", error);
    ElMessage.error("加载聊天室列表失败");
  } finally {
    loading.value = false;
  }
}

/**
 * 刷新当前条件下的列表
 */
async function handleRefresh() {
  await loadRoomsList();
  ElMessage.success("刷新成功");
}

/**
 * 打开/进入该聊天室
 * @param roomId 聊天室ID
 */
async function handleOpenRoom(roomId: number) {
  try {
    await store.selectRoom(roomId);
    router.push({ path: "/customer-service/inbox" });
  } catch (error) {
    console.error("进入聊天室失败:", error);
  }
}

/**
 * 删除聊天室
 * @param roomId 聊天室ID
 */
async function handleDeleteRoom(roomId: number) {
  // 确认删除
  const confirm = await ElMessageBox.confirm("确认删除该聊天室吗？删除后将无法恢复。", "删除聊天室", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  });
  if (!confirm) return;

  try {
    await deleteChatRoom(roomId, true);
    ElMessage.success("删除成功");
    await loadRoomsList();
  } catch (error) {
    console.error("删除聊天室失败:", error);
    ElMessage.error(error?.response?.data?.message || "删除聊天室失败");
  }
}

/**
 * 分页变化（页大小）
 */
async function handleSizeChange(size: number) {
  pagination.value.pageSize = size;
  pagination.value.page = 1;
  await loadRoomsList();
}

/**
 * 分页变化（页码）
 */
async function handleCurrentChange(page: number) {
  pagination.value.page = page;
  await loadRoomsList();
}

// 搜索关键词
async function handleSearch() {
  pagination.value.page = 1;
  await loadRoomsList();
}
// 重置搜索表单
function handleReset() {
  searchForm.value = {
    room_id: "",
    nickname: ""
  };
  pagination.value.page = 1;
  loadRoomsList();
}

// 初始加载 & 监听筛选
onMounted(() => {
  loadRoomsList();
});
</script>

<template>
  <div class="rooms-container">
    <!-- 头部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2>聊天室列表</h2>
        <el-tag type="info">总数 {{ pagination.total }}</el-tag>
      </div>
      <div class="toolbar-right">
        <el-button :icon="Refresh" circle @click="handleRefresh" />
      </div>
    </div>

    <!-- 搜索与筛选 -->
    <div class="filters">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="房间ID">
          <el-input v-model="searchForm.room_id" placeholder="搜索房间ID..." clearable />
        </el-form-item>
        <el-form-item label="参与者呢称">
          <el-input v-model="searchForm.nickname" placeholder="搜索用户昵称..." clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button type="info" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <div v-loading="loading" class="table-wrap">
      <el-table
        :data="rooms"
        :default-sort="{ prop: 'id', order: 'ascending' }"
        stripe
        height="calc(100vh - 260px)"
      >
        <el-table-column label="ID" prop="id" align="center" width="90" :sortable="true" />
        <el-table-column label="房间名" prop="name" align="center" min-width="180">
          <template #default="{ row }">
            <span class="name">{{ row.name || "未命名房间" }}</span>
            <el-tag size="small" :type="row.type === 'group' ? 'warning' : 'success'">{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="管理端用户" prop="participants[0].name" width="120" align="center">
          <template #default="{ row }">
            <el-tag type="primary">{{
              row.participants[0]?.type === "AdminUser"
                ? row.participants[0]?.name
                : row.participants[1]?.name || "-"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户端用户" prop="participants[1].name" width="120" align="center">
          <template #default="{ row }">
            <el-tag type="success">{{
              row.participants[1]?.type === "NormalUser"
                ? row.participants[1]?.name
                : row.participants[0]?.name || "-"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最后消息" align="center" min-width="220" :show-overflow-tooltip="true">
          <template #default="{ row }">
            <span class="mono">
              {{ typeof row.last_message === "string" ? row.last_message : row.last_message?.content || "-" }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" min-width="160">
          <template #default="{ row }">
            <span>
              {{ row.created_at ? new Date(row.created_at).toLocaleString() : "-" }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="更新时间" prop="updated_at" min-width="160">
          <template #default="{ row }">
            <span>{{ row.updated_at ? new Date(row.updated_at).toLocaleString() : "-" }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleOpenRoom(row.id)">进入</el-button>
            <el-button type="danger" size="small" @click="handleDeleteRoom(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.rooms-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #f5f7fa;

  .toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    background: white;
    border-bottom: 1px solid #e4e7ed;

    .toolbar-left {
      display: flex;
      gap: 12px;
      align-items: center;

      h2 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
      }
    }
  }

  .filters {
    display: flex;
    gap: 12px;
    padding: 16px 20px;
    background: white;
    border-bottom: 1px solid #e4e7ed;

    .el-input {
      flex: 1;
    }
  }

  .table-wrap {
    flex: 1;
    padding: 10px 0;
    overflow: hidden;

    .mono {
      font-family:
        ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
      padding-top: 12px;
    }
  }
}
</style>
